import crypto from 'crypto';

function generateSign(appid: string, q: string, salt: string, secretKey: string): string {
  // Step1: 按照 appid+q+salt+密钥 的顺序拼接字符串
  const stringToSign = `${appid}${q}${salt}${secretKey}`;

  // Step2: 对拼接后的字符串进行 MD5 加密，并返回 32 位小写签名
  return crypto.createHash('md5').update(stringToSign, 'utf8').digest('hex');
}

export function constructRequestParams(
  appid: string,
  secretKey: string,
  _from: string,
  _to: string,
  q: string,
  salt: string
): Record<string, string> | null {
  // 生成签名
  if (!(appid && secretKey && q)) return null;

  const sign = generateSign(appid, q, salt, secretKey);

  // 构造请求参数对象
  const params: Record<string, string> = {
    appid,
    q: encodeURIComponent(q), // 对 q 做 URL encode
    salt,
    sign,
    from: _from,
    to: _to
  };

  return params;
}
